#include "MySql.h"
#include <QSqlError>

MySql::MySql(QObject *parent)
{

}

MySql::~MySql()
{

}

void MySql::setfileInfo(const QFileInfo &fileinfo)
{
    fileInfo = fileinfo;
}

void MySql::setseller_name(const QString &sellname)
{
    seller_name = sellname;
}

void MySql::setbuyer_name(const QString &buyname)
{
    buyer_name = buyname;
}

QString MySql::getbuyer_name() const
{
    return buyer_name;
}

void MySql::setinvoice_number(const QString &invoicenumber)
{
    invoice_number = invoicenumber;
}

void MySql::setinvoice_date(const QString &invoicedate)
{
    invoice_date = invoicedate;
}

void MySql::settotal_amount(const float &totalamount)
{
    total_amount = totalamount;
}

void MySql::settax_amount(const float &taxamount)
{
    tax_amount = taxamount;
}

void MySql::setFileurl(const QString &url)
{
    downurl = url;
}

void MySql::settittle(const QString &tt)
{
    tittle = tt;
}

void MySql::setvalue(const QString &v)
{
    value = v;
}

QString MySql::getvalue() const
{
    return value;
}

QString MySql::gettittle() const
{
    return tittle;
}

QFileInfo MySql::getfileInfo() const
{
    return fileInfo;
}

QSqlDatabase MySql::connectSql()
{

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    // 设置数据库连接参数
    db.setHostName("8.148.65.226");     // 数据库服务器地址8.148.65.226
    db.setPort(3306);                // 端口号
    db.setDatabaseName("malloy"); // 数据库名
    db.setUserName("malloy");          // 用户名
    db.setPassword("Z54EJHWnY3K6xBsN");      // 密码
    return db;
}


QString MySql::SizeChange(qint64 size)
{
    QString sizeStr;
    if (size < 1024) {
        sizeStr = QString::number(size) + " B";
    } else if (size < 1024 * 1024) {
        sizeStr = QString::number(size / 1024.0, 'f', 2) + " KB";
    } else {
        sizeStr = QString::number(size / (1024.0 * 1024.0), 'f', 2) + " MB";
    }
    return sizeStr;
}
//执行0返回值的sql语句


void MySql::ExecSql(QString sqlcontent)
{

    QSqlQuery query;
    //查询最新的invoice_id
    QString idSql = ("SELECT MAX(invoice_id) FROM invoices;");

    int Maxinvoice_id;
    if (query.exec(sqlcontent)) {
        qDebug()<< "正在插入记录";
        query.exec(idSql);
        qDebug() <<"最新id为: "<<query.exec(idSql);
        while (query.next()) {
            // 通过索引访问列值
            Maxinvoice_id = query.value(0).toInt();
            qDebug()<<"当前最大id为:"<<Maxinvoice_id;
        }
        //同步插入invice_images表
        query.prepare("INSERT INTO invoice_images (invoice_id,file_name, file_size) VALUES (:invoice_id,:file_name, :file_size)");
        // 绑定值
        query.bindValue(":invoice_id",Maxinvoice_id);
        query.bindValue(":file_name", fileInfo.fileName());
        query.bindValue(":file_size", SizeChange((fileInfo.size())));
        query.exec();
        } else {
            qDebug() << "插入失败: " << query.lastError().text();
        }
}

